package org.benjamin.lending.controller;



import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.BasicResult;
import org.benjamin.lending.domain.GoPasswordForm;
import org.benjamin.lending.domain.LoginForm;
import org.benjamin.lending.domain.RegisterForm;
import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.service.EmailService;
import org.benjamin.lending.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "auth")
public class AuthController {
	
	private final Logger logger = LogManager.getLogger();
	
	@Autowired
	private MemberService memberService;

	@Autowired
	private EmailService emailService;
	
	/**
	 * 用户注册
	 * @param registerForm
	 * @param session
	 * @param modelMap
	 * @return
	 */
	@GetMapping(value = "register")
	public String toRegister(@ModelAttribute("registerForm") RegisterForm registerForm,HttpSession session,ModelMap modelMap){
		String token = DigestUtils.sha1Hex(""+System.currentTimeMillis());
		session.setAttribute("registerToken", token);
		modelMap.addAttribute("token",token);
		return "auth.register";
	}
	
	/**
	 * 用户注册操作
	 * @param registerForm
	 * @param bindingResult
	 * @param modelMap
	 * @return
	 */
	@PostMapping(value = "register")
	public String doRegister(@Valid RegisterForm registerForm,BindingResult bindingResult,ModelMap modelMap){
		if(!bindingResult.hasErrors()){
			if(registerForm.getPassword().equals(registerForm.getPasswords())){
				MemberInfo memberInfo = new MemberInfo();
				memberInfo.setUsername(registerForm.getUsername());
				String password = DigestUtils.md5Hex(registerForm.getPassword());
				memberInfo.setPassword(password);
				try{
					this.memberService.registerMember(memberInfo,registerForm.getCode());	
				}catch (IllegalArgumentException e) {
					logger.warn(e.getMessage());
					FieldError fieldError = new FieldError("username", "username", "用户名已经存在了");
					bindingResult.addError(fieldError);
					modelMap.addAttribute("registerForm",registerForm);
					return "auth.register";
				}
				return "redirect:/auth/login";
			}
		}
		modelMap.addAttribute("registerForm",registerForm);
		return "auth.register";
	}
	
	/**
	 * 用户登录
	 * @param loginForm
	 * @return
	 */
	@GetMapping(value = "login")
	public String toLogin(@ModelAttribute("loginForm") LoginForm loginForm){
		return "auth.login";
	}
	
	/**
	 * 用户登录操作
	 * @param loginForm
	 * @param bindingResult
	 * @return
	 */
	@PostMapping(value = "login")
	public String doLogin(@Valid @ModelAttribute("loginForm") LoginForm loginForm,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			
			return "auth.login";	
		}
/*		logger.info("您开始登录");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(),loginForm.getPassword());
		try{
			subject.login(token);	
		}catch(UnknownAccountException e){
			logger.warn("账号不存在");
			FieldError fieldError = new FieldError("username", "username", "用户名不存在");
			bindingResult.addError(fieldError);
			return "auth.login";
		}catch(IncorrectCredentialsException e){
			logger.warn("密码错误");
			FieldError fieldError = new FieldError("password", "password", "密码错误");
			bindingResult.addError(fieldError);
			return "auth.login";
		}catch(AuthenticationException e){
			FieldError fieldError = new FieldError("password", "password", "校验错误");
			logger.error(e.getMessage(),e);
			return "auth.login";
		}*/
		return "redirect:/user/index";
	}
	
	/**
	 * 用户注册发送短信验证码
	 * @param token
	 * @param mobiel
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "mobileSMS/token/{token}")
	public String mobileSMS(@PathVariable("token") String token,String mobiel,HttpServletRequest request, HttpSession session){
		Object temp = session.getAttribute("sendTime");
		boolean pass = false;
		if(temp == null){
			pass = true;
		}else{
			Long sendTime = (Long)temp;
			long time = System.currentTimeMillis() - sendTime;
			if(time >= 1000){
				logger.warn("当前用户请求发送短信频繁，{}",request.getRemoteAddr());
				return "";
			}
		}
		session.setAttribute("sendTime", System.currentTimeMillis());
		if(pass){
			if(StringUtils.isNotBlank(mobiel)){
				String registerToken = (String)session.getAttribute("registerToken");
				if(token.equals(registerToken)){
					logger.info("发送短信验证码");
					String code = RandomStringUtils.randomNumeric(6);
					logger.info("生产短信验证码{},发送电话号码：{}",code,mobiel);
					session.setAttribute("registerCode", code);
				}
			}
		}
		return "false";
	}

	/**
	 * 修改密码
	 * @return
	 */
	@ResponseBody
	@PostMapping("forgot")
	public BasicResult forgot(@Valid GoPasswordForm goPasswordForm,BindingResult bindingResult){
		BasicResult basicResult = new BasicResult();
		if(bindingResult.hasErrors()){
			basicResult.setStatus(1);
			basicResult.setMessage("邮件不符合");
			return basicResult;
		}
		try {
			this.emailService.getPassword(goPasswordForm.getEmail());
			basicResult.setStatus(0);
			basicResult.setMessage("邮件已经发送请签收");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			basicResult.setStatus(1);
			basicResult.setMessage(e.getMessage());
		}
		return basicResult;
	}

}
